package com.viewlibrary.water;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;

import com.viewlibrary.R;

import java.util.List;
import java.util.Random;

/**
 * 水滴容器
 */
public class WaterFlake extends FrameLayout {
    private List<String> contentList;
    private float centerTreeY;
    private int width;
    private int height;
    private int offset=5;
    private OnItemClickListener onItemClickListener;
    private boolean isCollect;
    public WaterFlake(@NonNull Context context) {
        this(context,null);
    }

    public WaterFlake(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public WaterFlake(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width=w;
        height=h;
    }

    public void setContentList(final List<String> contentList, float centerTreeY) {
        this.contentList = contentList;
        this.centerTreeY=centerTreeY;
        post(new Runnable() {
            @Override
            public void run() {
                removeAllViews();
                //添加水滴
                addWaterView(contentList);
           }
        });
    }

    private void addWaterView(List<String> contentList) {
        int[] randomX=randomCommon(1,8,contentList.size());
        int[] randomY=randomCommon(1,7,contentList.size());
        for (int i = 0; i < contentList.size(); i++) {
            //随机生成水滴球坐标
            WaterView waterView= (WaterView) LayoutInflater.from(getContext()).inflate(R.layout.view_water,WaterFlake.this,false);
            waterView.setX(randomX[i]*width*0.11f);
            waterView.setY(randomY[i]*height*0.06f);
            waterView.setContent(contentList.get(i));
            waterView.setTag(contentList.get(i));
            waterView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    //收集水滴能量点击事件及收集动画
                    if (onItemClickListener!=null){
                        onItemClickListener.onOnItemClick((WaterView) v);
                    }
                    addCollectAnimation(v);
                }
            });
            waterView.setTag(R.string.isUp,new Random().nextBoolean());
            waterView.setTag(R.string.offset,offset);
            addView(waterView);
            //添加水滴出现时动画
            addAppearAnimation(waterView);
            //添加水滴已出现时抖动动画
            addShowAnimation(waterView);
        }
    }

    /**
     * 收集能量时动画
     * @param v
     */
    private void addCollectAnimation(final View v) {
        if (isCollect)return;
        isCollect=true;
        //向下移动同时缓慢消失
        ObjectAnimator translateY=ObjectAnimator.ofFloat(v,"translationY",centerTreeY);
        ObjectAnimator alpha=ObjectAnimator.ofFloat(v,"alpha",1f,0f);

        AnimatorSet set=new AnimatorSet();
        set.setDuration(3000);
        set.setInterpolator(new LinearInterpolator());
        set.playTogether(translateY,alpha);
        set.start();
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                removeView(v);
                isCollect=false;
            }
        });
    }

    /**
     * 已经出现时动画
     * @param waterView
     */
    private void addShowAnimation(WaterView waterView) {
        //上下抖动
        boolean isUp= (boolean) waterView.getTag(R.string.isUp);
        int offsetValue= (int) waterView.getTag(R.string.offset);
        ObjectAnimator objectAnimator=null;
        if (isUp){
            objectAnimator=ObjectAnimator.ofFloat(waterView,"translationY",-offsetValue,offsetValue,-offsetValue);

        }else {
            objectAnimator=ObjectAnimator.ofFloat(waterView,"translationY",offsetValue,-offsetValue,offsetValue);
        }
        objectAnimator.setDuration(2000);
        objectAnimator.setRepeatMode(ValueAnimator.REVERSE);
        objectAnimator.setRepeatCount(ValueAnimator.INFINITE);
        objectAnimator.setInterpolator(new LinearInterpolator());
        objectAnimator.start();
    }

    /**
     * 出现时动画
     * @param waterView
     */
    private void addAppearAnimation(WaterView waterView) {
        //透明：0-1 ，缩放0-1
        waterView.setAlpha(0f);
        waterView.setScaleX(0f);
        waterView.setScaleY(0f);
        waterView.animate().alpha(1).scaleX(1f).scaleY(1f).setDuration(500).start();
    }
    public static int[] randomCommon(int min, int max, int n) {
        if (n > (max - min + 1) || max < min) {
            return null;
        }
        int[] result = new int[n];
        int count = 0;
        while (count < n) {
            int num = (int) ((Math.random() * (max - min)) + min);
            boolean flag = true;
            for (int j = 0; j < n; j++) {
                if (num == result[j]) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                result[count] = num;
                count++;
            }
        }
        return result;
    }
    public interface OnItemClickListener{
        void onOnItemClick(WaterView view);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

}
